import { Object, String } from 'lodash'
import { type TableColumnCtx } from 'element-plus'

export type filterInfoType = {
  [x:string]: {
    filters: Array<any>
    'filter-methods': Function
  }
}

export default {
  /**
   * 获取筛选数据
   * @param keys
   * @param data
   * @returns
   */
  getTableColumnFilter(keys: Array<string>, data: Array<any>, callback?: Function) {
    /**
     * 工具key 计算对应的列的filters 和 filter-methods
     */
    let filterInfo: any = {}
    keys.forEach((key: any) => {
      /**
       * 获取每行数据的 数据值 ，组装成 {text:'',value:''},
       */
      const filters = [...new Set(data.map(item => item[key]))].map(item => {
        return {
          text: item || '空值',
          value: item
        }
      })

      let timeoutId: number

      filterInfo[key] = {
        filters,
        filterMethod: (value: string | number | null, row: any, column: TableColumnCtx<any>) => {
          clearTimeout(timeoutId)
          timeoutId = setTimeout(() => {
            if (typeof callback == 'function') {
              callback(data)
            }
            clearTimeout(timeoutId)
          }, 500)

          const property = column['property']
          return row[property] == value
        }
      }
    })
    return filterInfo
  },

  getFilterInfoByKey(key: string, filterInfo: any) {
    if (!filterInfo || !filterInfo[key]) {
      return {
        filters: [],
        filterMethod: (value: string | number | null, row: any, column: TableColumnCtx<any>) => {
          const property = column['property']
          return row[property] == value
        }
      }
    }
    return filterInfo[key]
  }
}
